<?php
include_once "../init.inc.php";



/*00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*/
if (@$_REQUEST['everyones']){
    
     $id = (int)$_GET['everyones'];
     
     $sql = "SELECT p.ID, p.post_date, p.post_content, p.post_title
            FROM `posts` as p 
            WHERE p.ID = $id ";
     
    $result = mysql_query($sql) or die('Error, insert query failed');
    
   $row = mysql_fetch_assoc($result);
     
            $filename = $row['post_title'].".txt";
            $text = $row['post_content'];
    
    
    $testmethod="replaceEveryonesFavorites";
    $username = $_COOKIE['user_tbs'];
    $password = $_COOKIE['pwd_tbs'];
    //$text = $_REQUEST['textfavor'];
    //$protectedterms = $_REQUEST['protectever'];
    $quality = (int)$_COOKIE['tbsqual'];
    $maxsyns = (int)$_COOKIE['tbssyns'];
    $result = getTbs($testmethod ,$username, $password, $text, $protectedterms, $maxsyns, $quality);

    if (!$result['error']){
         getTextToBrowser($filename, $result['output']);
    }else outError($result['error']);
    //echo $result;
 
}
if (@$_REQUEST['rewrite']){
    
    $id = (int)$_GET['rewrite'];
     
     $sql = "SELECT p.ID, p.post_date, p.post_content, p.post_title
            FROM `posts` as p 
            WHERE p.ID = $id ";
     
    $result = mysql_query($sql) or die('Error, insert query failed');
    
   $row = mysql_fetch_assoc($result);
     
      $filename = $row['post_title'].".txt";
            $text = $row['post_content'];
    
    
    
      $testmethod="rewriteText";
      $username = $_REQUEST['user'];
      $password = $_REQUEST['pass'];
      //$text = $_REQUEST['rewritetext'];
      $protectedterms = $_REQUEST['protectrew'];
    
    
    $result = getTbs($testmethod ,$username, $password, $text, $protectedterms, $maxsyns, $quality);
    
    if (!$result['error']){
         getTextToBrowser($filename, $result['output']);
    }else outError($result['error']);
   // echo $result;
}

/*000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*/
function curl_post($url, $data, &$info){

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, curl_postData($data));
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_REFERER, $url);
  $html = trim(curl_exec($ch));
  curl_close($ch);

  return $html;
}

function curl_postData($data){

  $fdata = "";
  foreach($data as $key => $val){
    $fdata .= "$key=" . urlencode($val) . "&";
  }

  return $fdata;

}

function getTbs($testmethod ,$username, $password, $text, $protectedterms, $maxsyns, $quality=1){

$url = 'http://thebestspinner.com/api.php';

#$testmethod = 'identifySynonyms';
//$testmethod = 'replaceEveryonesFavorites';


# Build the data array for authenticating.

$data = array();
$data['action'] = 'authenticate';
$data['format'] = 'php'; # You can also specify 'xml' as the format.

# The user credentials should change for each UAW user with a TBS account.

//$data['username'] = 'your@useremail.com';
//$data['password'] = 'password';
$data['username'] = $username;
$data['password'] = $password;
# Authenticate and get back the session id.
# You only need to authenticate once per session.
# A session is good for 24 hours.
$output = unserialize(curl_post($url, $data, $info));

if($output['success']=='true'){
  # Success.
  $session = $output['session'];
  
  # Build the data array for the example.
  $data = array();
  $data['session'] = $session;
  $data['format'] = 'php'; # You can also specify 'xml' as the format.
  //$data['text'] = 'Losing weight can be a difficult thing to do.';
  $data['text'] = $text;
  $data['action'] = $testmethod;
  $data['protectedterms'] = $protectedterms;
  //$data['maxsyns'] = '3'; # The number of synonyms per term.
  
  if($testmethod=='replaceEveryonesFavorites'){
    # Add a quality score for this method.
    $data['quality'] = $quality;
    $data['maxsyns'] = $maxsyns; # The number of synonyms per term.
  }

  # Post to API and get back results.
  $output = curl_post($url, $data, $info);
  $output = unserialize($output);
  
  # Show results.
  //echo "<p><b>Method:</b><br>$testmethod</p>";
  //echo "<p><b>Text:</b><br>$data[text]</p>";
  
  $data['action'] = 'apiQuota';
  $quota = curl_post($url, $data, $info);
  $quota = unserialize($quota);
  
  if($output['success']=='true'){
      
        
             //echo "<p><b>Output:</b><br>" . str_replace("\r", "<br>", $output['output']) . "</p><p>Remaining quota: $quota[output]</p>";
              // return  str_replace("\r", "<br>", $output['output']);
                     return  $output;
        
                
         
  }
  else{
      
   // echo "<p><b>Error:</b><br>$output[error]</p>";
        return $output;
  }
}
else{
  # There were errors.
  //echo "<p><b>Error:</b><br>$output[error]</p>";
  return $output;
}

}
/*000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*/








function getTextToBrowser($filename, $text){

                header("Content-Disposition: attachment; filename=\"{$filename}\"");
                //header("Last-Modified: {$ftime}");
                //header("Content-Length: ".($fsize-$range));
                //header("Accept-Ranges: bytes");
                //header("Content-Range: bytes {$range}-".($fsize - 1)."/".$fsize);

                // подправляем под IE что б не умничал
                if(isset($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'],'MSIE'))
                Header('Content-Type: application/force-download');
                else
                Header('Content-Type: application/octet-stream');

                //while(!feof($handle)) {
                //    $buf = fread($handle,512);
                    print($text);
                //}

}
function outError($error){
    include_once "header.php";
        ?>
            <div class="alert alert-error"><?=@$error?></div>

        <?php
    include_once "footer.php"; 
  
}











?>
